package com.tungse.juc;

import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier
 * 简单理解为加法计数器就行
 */
public class CyclicBarrier_Demo {

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5,()->{
            System.out.println("所有人都到齐了，开始执行任务");
        });
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + "到位了");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            },String.valueOf(i)).start();
        }

    }

    @Test
    public void test() throws InterruptedException {
        // 分阶段处理大数据（3个阶段）
        CyclicBarrier barrier = new CyclicBarrier(4, () ->System.out.println("阶段完成！"));
        System.out.println("111");
        for (int i = 0; i < 4; i++) {
            final int finalI = i;
            new Thread(() -> {
                try {
                    System.out.println(finalI + "任务1");
                    barrier.await();  // 等待所有线程完成阶段1
                    System.out.println(finalI + "任务2");
                    barrier.await();  // 等待阶段2
                    System.out.println(finalI + "任务3");
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        Thread.currentThread().join();
    }
}
